document.addEventListener('DOMContentLoaded', function() {
    const addIngredientForm = document.getElementById('addIngredientForm');
    const resetBtn = document.getElementById('resetBtn');
    const successMessage = document.getElementById('successMessage');
    const photoInput = document.getElementById('photo');
    
    // 表单提交处理
    addIngredientForm.addEventListener('submit', function(e) {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        // 将 ingredientName 重命名为 name
        const ingredientName = formData.get('ingredientName');
        formData.delete('ingredientName');
        formData.append('name', ingredientName);
        // productionDate 改名为 production_date
        const productionDate = formData.get('productionDate');
        formData.delete('productionDate');
        formData.append('production_date', productionDate);
        // 其余字段名与表单一致，无需处理
        formData.append('created_by', sessionStorage.getItem('userId'));
        fetch('http://localhost:3000/api/ingredients', {
            method: 'POST',
            headers: {
                'Authorization': sessionStorage.getItem('token') || '',
                // 其他header按需保留
            },
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            if (data.message === '添加成功') {
                showCenterModal('添加成功！');
                form.reset();
            } else {
                showCenterModal(data.error || '添加失败');
            }
        })
        .catch(err => {
            showCenterModal('请求失败');
            console.error(err);
        });
    });
    
    // 重置按钮
    resetBtn.addEventListener('click', function() {
        addIngredientForm.reset();
        successMessage.style.display = 'none';
    });
    
    // 图片预览功能
    photoInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // 验证文件类型
            if (!file.type.startsWith('image/')) {
                showCenterModal('请选择图片文件');
                photoInput.value = '';
                return;
            }
            
            // 验证文件大小（限制为5MB）
            if (file.size > 5 * 1024 * 1024) {
                showCenterModal('图片文件大小不能超过5MB');
                photoInput.value = '';
                return;
            }
            
            // 创建预览（可选功能）
            const reader = new FileReader();
            reader.onload = function(e) {
                // 可以在这里添加图片预览功能
                console.log('图片已选择:', file.name);
            };
            reader.readAsDataURL(file);
        }
    });
    

    
    // 屏幕中心弹窗
    function showCenterModal(message, callback) {
        let modal = document.createElement('div');
        modal.style.position = 'fixed';
        modal.style.left = '0';
        modal.style.top = '0';
        modal.style.width = '100vw';
        modal.style.height = '100vh';
        modal.style.background = 'rgba(0,0,0,0.18)';
        modal.style.display = 'flex';
        modal.style.alignItems = 'center';
        modal.style.justifyContent = 'center';
        modal.style.zIndex = '9999';
        modal.innerHTML = `<div style=\"background:#fff;border-radius:12px;box-shadow:0 4px 24px #0002;padding:32px 36px;min-width:320px;text-align:center;\">
            <div style='font-size:20px;font-weight:600;margin-bottom:12px;color:#388e3c;'>提示</div>
            <div style='font-size:16px;margin-bottom:24px;'>${message}</div>
            <button id='centerModalBtn' style='background:#4caf50;color:#fff;border:none;border-radius:6px;padding:8px 32px;font-size:16px;cursor:pointer;'>确定</button>
        </div>`;
        document.body.appendChild(modal);
        document.getElementById('centerModalBtn').onclick = function() {
            document.body.removeChild(modal);
            if (callback) callback();
        };
    }
    
    // 设置默认日期为今天
    const today = new Date().toISOString().split('T')[0];
    document.getElementById('productionDate').value = today;
}); 